package org.hive.testserver.domain.model;

public class Test implements Entity {

	private TestRun testRun;
	private String name;
	private int timesExecuted = 0;
	private long totalDuration = 0;
	private TestState currentTestState = TestState.UNTESTED;
	private boolean isFinished = false;

	public Test(String name) {
		super();
		this.name = name;
	}

	public String getName() {
		return name;
	}

	void setTestRun(TestRun testRun) {
		this.testRun = testRun;
	}

	public TestRun getTestRun() {
		return testRun;
	}

	public String getId() {
		return testRun.getId()+":"+name;
	}

	public TestState currentState() {
		return currentTestState;
	}
	
	public void updateState(TestState resultState) {
		currentTestState = resultState;
		testRun.testUpdatedState(this);
	}

	public int timesExecuted() {
		return timesExecuted;
	}

	public void updateFromExecution(TestState testState, long duration) {
		timesExecuted += 1;
		totalDuration += duration;
		updateState(testState);
	}
	
	public long averageDuration() {
		if (timesExecuted == 0) {
			return 0;
		} else {
			return totalDuration / timesExecuted;
		}
	}

	public boolean isFinished() {
		return isFinished;
	}
	
	public void beFinished() {
		testHistory().addFinishedRun(currentTestState, averageDuration());
		isFinished = true;
	}
	
	public TestHistory testHistory() {
		return testRun.getProject().getProjectHistory().lookupTestHistoryOrCreate(name);
	}

	public void beUnfinished() {
		isFinished = false;
	}
}
